import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'dart:io';

/// 自定义Dio客户端
/// 用于处理MinIO预签名URL的请求
class DioClient {
  static Dio? _instance;

  /// 获取Dio实例
  static Dio getInstance({
    String? baseUrl,
    Map<String, dynamic>? headers,
    int connectTimeout = 15000,
    int receiveTimeout = 15000,
  }) {
    if (_instance == null) {
      final options = BaseOptions(
        baseUrl: baseUrl ?? '',
        connectTimeout: Duration(milliseconds: connectTimeout),
        receiveTimeout: Duration(milliseconds: receiveTimeout),
        headers: headers ?? {},
      );

      _instance = Dio(options);

      // 添加日志拦截器
      _instance!.interceptors.add(
        LogInterceptor(
          requestBody: kDebugMode,
          responseBody: kDebugMode,
          logPrint: (obj) {
            if (kDebugMode) {
              print('[Dio] $obj');
            }
          },
        ),
      );
    }

    return _instance!;
  }

  /// 重置Dio实例
  static void resetInstance() {
    _instance = null;
  }
}

/// 图片加载工具类
/// 使用Dio加载图片，处理MinIO预签名URL
class ImageLoader {
  /// 使用Dio加载图片
  static Future<Uint8List?> loadImage(String url) async {
    try {
      final dio = DioClient.getInstance();
      final response = await dio.get(
        url,
        options: Options(
          responseType: ResponseType.bytes,
          followRedirects: true,
          validateStatus: (status) => status != null && status < 500,
        ),
      );

      if (response.statusCode == 200) {
        return Uint8List.fromList(response.data);
      } else {
        print('加载图片失败，状态码: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('加载图片出错: $e');
      return null;
    }
  }
}
